CC=gcc
CXX=g++
LD=g++

BIN=./bin/

INCLUDES=-I/usr/include -I./include 
LIBS=-lpthread
LIBSEARCHPATH=-L/usr/lib/

CFLAGS=-pipe -std=gnu99 -Wall -g 
CXXFLAGS=$(INCLUDES) -pipe -Wall -Wno-unused-but-set-variable -std=c++11 -g -O0
LDFLAGS=$(LIBSEARCHPATH) $(LIBS)
OUTPUT=ibrc_p2p_client

SRC_C=$(shell find ./src -name "*.c" -printf %p\ )
SRC_CXX=$(shell find ./src -name "*.cpp" -printf %p\ )
OBJ=$(addprefix $(BIN),$(notdir $(patsubst %.c,%.o,$(SRC_C)))) $(addprefix $(BIN),$(notdir $(patsubst %.cpp,%.o,$(SRC_CXX))))
HEADER=$(shell find ./include -name "*.hpp" -printf %p\ )

.PHONY: all clean print link
.DEFAULT_GOAL:= all


all: link

	
link: $(OBJ)
	@echo "Linking!"
	@echo " LD   " $(OUTPUT)
	@$(LD) $(OBJ)  -o $(OUTPUT) $(LDFLAGS)  
	@echo
	
	
print:
	@echo
	@echo "Header files:"
	@echo $(HEADER)
	@echo "C Source files:"
	@echo $(SRC_C)
	@echo "CPP Source files:"
	@echo $(SRC_CXX)
	@echo "Object files:"
	@echo $(OBJ)
	@echo


clean:
	-rm $(OUTPUT) $(BIN)/*
	
#
# Functions
#	
	
#$(call c-one-compile-rule,object_file,source_file)
define c-one-compile-rule
$1: $2 $(HEADER)
	@echo " CC   "	$$<
	@$(CC) $(CFLAGS) -c $$< -o $$@
endef

#$(call c-one-compile-rule,object_file,source_file)
define cxx-one-compile-rule
$1: $2 $(HEADER)
	@echo " CXX  "		$$<
	@$(CXX) $(CXXFLAGS) -c $$< -o $$@
endef
 
#$(call c-source-to-object, source_file)
c-source-to-object = $(BIN)$(notdir $(subst .c,.o,$(filter %.c,$1)))

#$(call c-source-to-object, source_file)
cxx-source-to-object = $(BIN)$(notdir $(subst .cpp,.o,$(filter %.cpp,$1)))

#
# Create compile rules
#

$(foreach f, $(SRC_C),$(eval $(call c-one-compile-rule,$(call c-source-to-object,$f),$f)))

$(foreach f, $(SRC_CXX),$(eval $(call cxx-one-compile-rule,$(call cxx-source-to-object,$f),$f)))

